// miniprogram/pages/NX_detailMission/detailMission.js
import {
  figureStyle,
  getLocalString,
  getDate,
  ONE_DAY
} from '../../library/configGantt'
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {

    master: false,
    self: false,
    missionId: null,
    missionDetail: null,
    missionList: [{
      name: '无',
      _id: null
    }],
    missionListLoad: false,
    projectInfo: null,
    delay: false,
    estimation: false,
    history: [],

    startValue: [0],
    missionFlow: [],

    scrollTop:0,
    lastTouchY:0,
    lastTouchTime:0,
    speed:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      master: options.master === 'true',
      missionId: options.missionId
    })
  },
  init() {
    return new Promise((resolve) => {
      const globalMission = getApp().globalData.tempMissionDetail;
      //如果有全局缓存
      if (globalMission) {
        this.setData({
          missionDetail: globalMission
        })
        this.dealMissionInfo(globalMission).then(resolve)
        //清除全局缓存
        getApp().globalData.tempMissionDetail = null;
        return;
      } else {
        //否则从数据库中拉取
        wx.cloud.callFunction({
          name: 'getMissionInfo',
          data: {
            id: this.data.missionId
          }
        }).then(res => {
          const missionDetail = res.result;
          // console.log(res)
          const {
            percent,
            color
          } = figureStyle(missionDetail)
          missionDetail.percent = percent;
          missionDetail.color = color;
          this.setData({
            missionDetail,
          })
          this.dealMissionInfo(missionDetail).then(resolve);
          return;
        })
      }
    })
  },
  dealMissionInfo(info, requireAll = true) {
    return new Promise(resolve => {
      const allQuests = [];
      if (info && info.projectId && requireAll) {
        allQuests.push(
          db.collection('group').doc(info.projectId).get().then(res => {
            this.setData({
              projectInfo: res.data
            })
          })
        )
      }
      if (info.init) {
        //如果任务已被初始化
        let self = false,
          delay = false,
          estimation = false;
        if (info.userId === getApp().globalData.userInfo._id) self = true;
        if (info.front.length && requireAll) {
          estimation = [];
          const promiseList = [];
          for (let i = 0; i < info.front.length; i++) {
            promiseList.push(wx.cloud.callFunction({
              name: 'getMissionInfo',
              data: {
                id: info.front[i]
              }
            }).then(res => {
              estimation[i] = res.result
            }));
          }
          allQuests.push(Promise.all(promiseList).then(() => {
            this.setData({
              estimation
            })
          }))
        };
        const today = new Date().getTime();
        const end = getDate(info.end).getTime();
        if (end < today && info.status !== 'done') {
          delay = parseInt((today - end) / ONE_DAY);
        }
        this.setData({
          self,
          delay
        });
      } else {
        //等待处理委托
        if (info.userId === getApp().globalData.userInfo._id) this.setData({
          self: true
        });

        wx.setNavigationBarTitle({
          title: `${this.data.missionDetail.consignorClient.userName}的委托`
        })
        const gMission = getApp().globalData.selfMission;
        if (gMission.length) {
          this.setData({
            missionList: gMission.filter(item => item._id !== this.data.missionDetail._id),
            missionListLoad: true
          })
        } else {
          allQuests.push(
            wx.cloud.callFunction({
              name: 'login',
              data: {
                needDetail: true
              }
            }).then(res => {
              // console.log(res.resultz);
              if (res.result && res.result.mission) {
                if (!res.result.mission || !res.result.mission.length) {
                  this.setData({
                    missionList: [{
                      _id: null,
                      name: '无'
                    }],
                    missionListLoad: true
                  })
                } else {
                  this.setData({
                    missionList: res.result.mission.filter(item => item._id !== this.data.missionDetail._id),
                    missionListLoad: true
                  })
                }
              }
            })
          )
        }

      }
      //获得任务历史
      allQuests.push(wx.cloud.callFunction({
        name: 'getMissionHistory',
        data: {
          missionId: info._id
        }
      }).then(res => {
        //处理时间
        res.result.forEach(item => {
          const tempTime = new Date(item.time);
          let hour = '00' + tempTime.getHours();
          let minute = '00' + tempTime.getMinutes();
          hour = hour.substr(hour.length - 2, 2);
          minute = minute.substr(minute.length - 2, 2);
          item.time = `${tempTime.getMonth() + 1}-${tempTime.getDate()} ${hour}:${minute}`
        })
        this.setData({
          history: res.result.reverse()
        })
      }))
      //获得子任务
      allQuests.push(
        db.collection('missionFlow').where({
          missionId: info._id
        }).orderBy('createTime','desc').get().then(res => {
          this.setData({
            missionFlow: res.data
          })
        }));
      Promise.all(allQuests).then(resolve)
    })
  },
  starMission() {
    this.data.missionDetail.star = !this.data.missionDetail.star;
    wx.cloud.callFunction({
      name: 'updateMissionInfo',
      data: {
        missionId: this.data.missionDetail._id,
        star: this.data.missionDetail.star
      }
    }).then(() => {
      this.dealMissionInfo(this.data.missionDetail, false)
    })
    this.setData({
      missionDetail: this.data.missionDetail
    })
  },
  finMission() {
    this.data.missionDetail.status = this.data.missionDetail.status == 'done' ? 'doing' : 'done'
    // db.collection('mission').doc(this.data.missionDetail._id).update({
    //     data: {
    //         status: this.data.missionDetail.status
    //     }
    // });
    wx.cloud.callFunction({
      name: 'updateMissionInfo',
      data: {
        missionId: this.data.missionDetail._id,
        status: this.data.missionDetail.status
      }
    }).then(() => {

      this.dealMissionInfo(this.data.missionDetail, false)
    })
    this.setData({
      missionDetail: this.data.missionDetail
    })
  },
  changeMission() {
    const goChangePage = () => {
      getApp().globalData.tempMissionDetail = this.data.missionDetail;
      wx.navigateTo({
        url: `../NX_newMission/newMission?missionId=${this.data.missionDetail._id}&projectId=${this.data.missionDetail.projectId}`
      })
    }
    if (this.data.missionDetail.back && this.data.missionDetail.back.length) {
      wx.showModal({
        title: '提示',
        content: '存在其他任务依赖于此任务，请慎重修改',
        confirmText: '了解',
        success: res => {
          if (res.confirm) {
            goChangePage()
          }
        }
      })
    } else {
      goChangePage();
    }

  },
  delMission() {
    if (this.data.missionDetail.back && this.data.missionDetail.back.length) {
      wx.showToast({
        title: '存在后置任务，无法删除该任务',
        icon: 'none'
      })
    } else {
      wx.showModal({
        title: '确认',
        content: '删除操作不可逆，是否删除任务？',
        confirmText: '删除',
        confirmColor: '#b62c2c',
        success: (res) => {
          if (res.confirm) {
            wx.cloud.callFunction({
              name: 'delMission',
              data: {
                id: this.data.missionDetail._id
              }
            }).then(() => {
              wx.navigateBack({
                detla: 1
              })
            }).catch((err) => {
              console.log(err);
              wx.showToast({
                icon: 'none',
                title: '发生错误请重试'
              })
            })
          }
        }
      })
    }
  },
  selectChange(e) {
    // console.log(e);
    this.setData({
      startValue: e.detail.value
    })
  },
  selectConfirmed() {
    const missionItem = this.data.missionList[this.data.startValue[0]];
    if (missionItem && missionItem._id) {
      const sourceId = this.data.missionDetail._id,
        targetId = missionItem._id
      wx.showModal({
        title: '确认',
        content: '将委托合并至 ' + missionItem.name + ' 确定吗？',
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({
              mask: true,
              title: '请稍后'
            })
            wx.cloud.callFunction({
              name: 'mergeMission',
              data: {
                sourceId,
                targetId
              }
            }).then(() => {
              // this.init();
              wx.hideLoading();
              // wx.navigateBack({
              // delta: 1
              // });
              wx.navigateTo({
                url: './detailMission?master=true&missionId=' + targetId
              })
            })
          }
        }
      })

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.init();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  addMissionFlow() {
    for (const item of this.data.missionFlow) {
      if (!item.init) {
        return;
      }
    }
    this.data.missionFlow.unshift({
      init: false,
      flowName: '',
      _id: 0
    })
    this.setData({
      missionFlow: this.data.missionFlow
    })
  },
  changeFlowName(e) {
    // console.log(e)
    this.data.missionFlow[e.target.dataset.index].flowName = e.detail.value;
    this.setData({
      missionFlow: this.data.missionFlow
    })
  },
  confirmCreateFlow(e) {
    console.log(e)
    const target = this.data.missionFlow[e.target.dataset.index]
    console.log(target)
    if (target && target.flowName && target.flowName.length) {
      // wx.showLoading({
      //   title: '请稍后',
      // });
      target.init=true;
      this.setData({
        missionFlow:this.data.missionFlow
      })
      wx.cloud.callFunction({
        name: 'makeMissionFlow',
        data: {
          missionId: this.data.missionId,
          flowName: target.flowName
        }
      }).then(res => {
        console.log(res);
        this.init().then(() => {
          // wx.hideLoading();
        })

      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '请输入流程名称',
      })
    }
  },
  cancelCreateFlow(e){
    const {
      index
    } = e.target.dataset;
    this.data.missionFlow.splice(index,1);
    this.setData({
      missionFlow:this.data.missionFlow
    })
  },
  delFlow(e) {
    // console.log(e)
    const {
      id,
      index
    } = e.target.dataset;
    this.data.missionFlow.splice(index, 1);
    //调用API
    wx.cloud.callFunction({
      name: 'delMissionFlow',
      data: {
        flowId: id
      }
    }).then(res => {
      console.log(res);
      this.init();
    })
    setTimeout(() => {
      this.setData({
        missionFlow: this.data.missionFlow
      })
    }, 500)

  },
  finFlow(e) {
    // console.log(e)
    const {
      id,
      index
    } = e.target.dataset;
    // this.data.missionFlow.splice(index, 1);
    const status = this.data.missionFlow[index].status === 'done' ? 'doing' : 'done';
    this.data.missionFlow[index].status = status;
    //调用API
    wx.cloud.callFunction({
      name: 'updateMissionFlow',
      data: {
        flowId: id,
        status
      }
    }).then(res => {
      console.log(res);
      this.init();
    })

    this.setData({
      missionFlow: this.data.missionFlow
    })

  },
  ystart(e){
    // console.log(e)
    if(e.detail&&e.detail.y){
      this.data.lastTouchY=e.detail.y,
      this.data.lastTouchTime=e.timeStamp;
      this.data.speed=0;
    }
  },
  ymove(e){
    // console.log(e)
    if(e.detail&&e.detail.y){
      const deltaY=this.data.lastTouchY-e.detail.y;
      this.data.speed=(this.data.speed+deltaY/(e.timeStamp-this.data.lastTouchTime))/2;
      this.data.lastTouchTime=e.timeStamp;
      wx.pageScrollTo({
        scrollTop: this.data.scrollTop+deltaY,
        duration: 0,
      })
      this.data.lastTouchY=e.detail.y;
    }
  },
  yend(e){
    // console.log(e)
      if(Math.abs(this.data.speed)>0){
        wx.pageScrollTo({
          scrollTop: this.data.scrollTop + this.data.speed*200,
          duration: 250,
        })
        this.data.speed=0;
      }
  },
  onPageScroll(e) {
    this.data.scrollTop=e.scrollTop;
  },
})